package com.geeke.sys.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang3.StringUtils;

import com.geeke.common.service.CrudService;
import com.geeke.common.data.PageRequest;
import com.geeke.common.data.Parameter;
import com.geeke.config.exception.CommonJsonException;

import com.geeke.sys.dao.DictTypeDao;
import com.geeke.sys.dao.DictItemDao;
import com.geeke.sys.entity.DictType;
import com.geeke.sys.entity.DictItem;
import com.geeke.sys.service.DictItemService;
import com.geeke.utils.ResultUtil;
import com.geeke.utils.constants.ErrorEnum;
import com.google.common.collect.Lists;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldCallback;
import org.springframework.util.ReflectionUtils.FieldFilter;
import java.lang.reflect.Field;

/**
 * 字典类型表 Service
 * @author
 * @version
 */
@Service("dictTypeService")
@Transactional(readOnly = true)
public class DictTypeService extends CrudService<DictTypeDao, DictType> {

    // 从表Dao  
    @Autowired
    private DictItemDao dictItemDao;
    
    // 从表Service
    @Autowired
    private DictItemService dictItemService;

    @Override
    public DictType get(String id) {
        DictType dictType = super.get(id);

        List<Parameter> params = null;
        PageRequest pageRequest;

        /*获取从表列表*/
        params = Lists.newArrayList();
        params.add(new Parameter("dictItem.dict_type_id", "=", dictType.getId()));
        pageRequest = new PageRequest(params);
        dictType.setDictItemList(dictItemDao.listAll(pageRequest));

        return dictType;
    }

    @Transactional(readOnly = false)
    @Override
    public DictType save(DictType dictType) {
        // 重复性检查
        List<Parameter> params = Lists.newArrayList();
        // 编号重复性检查
        params.clear();
        params.add(new Parameter("dictType.code", "=", dictType.getCode()));
        // 表有del_flag字段，则使用delFlag
        params.add(new Parameter("dictType.del_flag", "=", dictType.getDelFlag()));

        if(!StringUtils.isBlank(dictType.getId())) {
          params.add(new Parameter("dictType.id", "<>", dictType.getId()));
        }

        if(this.dao.count(new PageRequest(params)) > 0) {
            throw new CommonJsonException(ResultUtil.warningJson(ErrorEnum.E_50001, "已存在相同编号"));
        }

        DictType dictTypeTemp = super.save(dictType);

        /* 保存从表数据 */
        saveDictItemList(dictTypeTemp);

        return dictTypeTemp;
    }

    @Override
    @Transactional(readOnly = false)
    public int delete(DictType dictType) {
        List<Parameter> params = null;
        PageRequest pageRequest;

        /* 处理从表 */
        params = Lists.newArrayList();
        params.add(new Parameter("dictItem.dict_type_id", "=", dictType.getId()));
        pageRequest = new PageRequest(params);
        dictType.setDictItemList(dictItemDao.listAll(pageRequest));

        if (dictType.getDictItemList() != null && dictType.getDictItemList().size() > 0) {
            dictItemService.bulkDelete(dictType.getDictItemList());
        }

        int rows = super.delete(dictType);
        return rows;
    }


    /* 保存从表数据 */
    private void saveDictItemList(DictType dictType) {
        List<Parameter> params = Lists.newArrayList();

        params.add(new Parameter("dictItem.dict_type_id", "=", dictType.getId()));
        PageRequest pageRequest = new PageRequest(params);
        List<DictItem> list_DictItem = dictItemDao.listAll(pageRequest);

        List<DictItem> deletes = Lists.newArrayList(); // 删除列表
        List<DictItem> inserts = Lists.newArrayList(); // 添加列表
        List<DictItem> updates = Lists.newArrayList(); // 更新列表
        
        // 找出需要删除的记录
        for (DictItem dictItemSaved : list_DictItem) {
            boolean found = false;
            for (DictItem dictItem : dictType.getDictItemList()) {
                if (dictItemSaved.getId().equals(dictItem.getId())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                deletes.add(dictItemSaved);
            }
        }
        
        // 批量删除
        if (deletes.size() > 0) {
            dictItemService.bulkDelete(deletes);
        }
        
        // 分拣需要新增和更新的记录
        for (DictItem dictItem : dictType.getDictItemList()) {
            if (StringUtils.isBlank(dictItem.getId())) {
                dictItem.setDictType(dictType);
                inserts.add(dictItem);
            } else {
                updates.add(dictItem);
            }
        }
        
        // 批量更新和新增
        if (updates.size() > 0) {
            dictItemService.bulkUpdate(updates);
        }
        if (inserts.size() > 0) {
            dictItemService.bulkInsert(inserts);
        }
    }
} 